package com.ea.common.utils;


import com.ea.common.auth.AdminFeign;
import com.ea.common.auth.NowUser;
import com.ea.common.result.Result;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Component
public class UserGetter {
    @Resource
    AdminFeign authFeign;

    // 获得当前的用户
    //获得当前的用户
    public NowUser getNowUser() {
        Result<NowUser> result = authFeign.getNowUserByUsername(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        return result.getData();
    }

    public String getUsername() {
        return ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
    }

    public String getToken() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull
                (RequestContextHolder.getRequestAttributes())).getRequest();
        return request.getHeader("Authorization");
    }
}
